package com.gdip.service.impl;

import com.gdip.common.dtos.ResponseResult;
import com.gdip.common.enums.AppHttpCodeEnum;
import com.gdip.mapper.CommentMapper;
import com.gdip.mapper.ProblemMapper;
import com.gdip.mapper.SchoolClassMapper;
import com.gdip.po.CommentPo;
import com.gdip.po.ProblemPo;
import com.gdip.po.SchoolClass;
import com.gdip.service.CommentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * ClassName: CommentServiceImpl
 * Package: com.gdip.service.impl
 *
 * @Author 南浔
 * @Create 2024/4/11 23:14
 * @Version 1.0
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Resource
    CommentMapper commentMapper;
    @Resource
    ProblemMapper problemMapper;
    @Resource
    SchoolClassMapper schoolClassMapper;


    // 增加评论
    @Override
    public ResponseResult insert_comment(CommentPo commentPo) {
        // 参数检查
        if(commentPo.getUserId() < 1 || commentPo.getProblemId() < 1 || commentPo.getScore() < 0 ||
                commentPo.getScore() > 5 || commentPo.getContent().trim().isEmpty() || commentPo.getContent().length() > 255){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else{
            int count = commentMapper.insertComment(commentPo);
            if(count != 1){
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    // 单一查询信息(根据问题id和用户id)
    @Override
    public ResponseResult getComment(int userId, int problemId) {
        if(userId < 1 || problemId < 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else {
            CommentPo commentPo = commentMapper.getComment(userId, problemId);
            return ResponseResult.okResult(commentPo);
        }
    }

    // 查询所有评论，返回创建时间和评分
    @Override
    public ResponseResult getCommentAll() {
        List<CommentPo> list = commentMapper.getCommentAll();
        return ResponseResult.okResult(list);
    }

    // 按部门查询对应的所有评论，返回每条记录的创建时间和评分
    @Override
    public ResponseResult getCommentByClass(int classId) {
        if(classId < 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else{
            // 1.根据部门id查问题表，查出所有对应问题id
            List<ProblemPo> problemPos = problemMapper.getProblemIdByClassId(classId);
            if (problemPos == null || problemPos.isEmpty()) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 2.根据问题id查评论表，查出所有评论Id
            List<CommentPo> commentPos = new ArrayList<>();
            problemPos.forEach(problem -> {
                int problemId = problem.getId();
                CommentPo commentPo = commentMapper.getCommentByProblemId(problemId);
                if(commentPo != null){
                    commentPos.add(commentPo);
                }
            });

            return ResponseResult.okResult(commentPos);
        }
    }

    // 整体满意度
    @Override
    public ResponseResult commentAll() {
        List<CommentPo> commentPos = commentMapper.getCommentAll();
        if(commentPos == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Map<String, Integer> map = new HashMap<>();
        int[] counts = new int[5];

        commentPos.forEach(commentPo -> {
            int score = commentPo.getScore();
            if(score == 5){
                counts[score - 1]++;
            }else if(score == 4){
                counts[score - 1]++;
            }else if(score == 3){
                counts[score - 1]++;
            }else if(score == 2){
                counts[score - 1]++;
            }else if(score == 1){
                counts[score - 1]++;
            }
        });
        map.put("五星", counts[4]);
        map.put("四星", counts[3]);
        map.put("三星", counts[2]);
        map.put("二星", counts[1]);
        map.put("一星", counts[0]);

        return ResponseResult.okResult(map);
    }

    // 按年份统计表
    @Override
    public ResponseResult commentYear() {
        List<CommentPo> commentPos = commentMapper.getCommentAll();
        if(commentPos == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Map<Integer, Double> map = new HashMap<>();
        double[] scores = new double[5];  // 放对应年份分数
        int[] counts = new int[5];  // 放对应年份含有的意见数量

        // 分值算法：总分固定100分，就是刻度意思。然后数据，假如10个问题，9个5分，一个1分，换算就是（9 乘5+1乘1）/50，46/50,就是92/100，算92分。

        int year_now = LocalDateTime.now().getYear();  // 当前年份
        commentPos.forEach(commentPo -> {
            int score = commentPo.getScore();  // 分数
            int year = commentPo.getCreateTime().getYear();  // commentPo年份

            if(year == year_now){
                scores[4] += score;
                counts[4]++;
            }else if(year == (year_now - 1)){
                scores[3] += score;
                counts[3]++;
            }else if(year == (year_now - 2)){
                scores[2] += score;
                counts[2]++;
            }else if(year == (year_now - 3)){
                scores[1] += score;
                counts[1]++;
            }else if(year == (year_now - 4)){
                scores[0] += score;
                counts[0]++;
            }
        });

        // 换算分数
        for(int i = 0;i < 5;i++){
            if(counts[i] == 0){  // 处理极端情况
                scores[i] = 100.00;
            }else{
                scores[i] = (scores[i] / (counts[i] * 5)) * 100;
            }
        }

        map.put(year_now, scores[4]);
        map.put(year_now - 1, scores[3]);
        map.put(year_now - 2, scores[2]);
        map.put(year_now - 3, scores[1]);
        map.put(year_now - 4, scores[0]);

        return ResponseResult.okResult(map);
    }

    // 部门满意度排名
    @Override
    public ResponseResult comment_classRank() {
        // 查询到所有部门
        List<SchoolClass> schoolClasses = schoolClassMapper.findAllSchoolClasses();
        if(schoolClasses == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Map<String, Double> map = new HashMap<>();  // 返回对象
        Double[] score = new Double[1];  // 分数
        int[] count = new int[1];  // 意见数量

        // 用部门id去查询对应所有意见信息
        schoolClasses.forEach(schoolClass -> {  // 循环每个部门
            score[0] = 0.0;
            count[0] = 0;
            // 获取部门id
            int class_id = schoolClass.getId();
            // 查询到当前部门所有的意见信息
            List<ProblemPo> problemPos = problemMapper.getProblemIdByClassId(class_id);
            if(problemPos == null){
                score[0] = 100.0;
            }else{
                problemPos.forEach(problemPo -> {  // 循环当前部门所有的意见信息
                    int problem_id = problemPo.getId();
                    // 用意见id查询评价id
                    CommentPo commentPo = commentMapper.getCommentByProblemId(problem_id);
                    if(commentPo != null){
                        score[0] += commentPo.getScore();
                        count[0]++;
                    }
                });
                // 转换分值
                if(count[0] == 0){
                    score[0] = 100.0;
                }else{
                    score[0] = (score[0] / (count[0] * 5)) * 100;
                }
            }
            map.put(schoolClass.getClassName(), score[0]);
        });

        return ResponseResult.okResult(map);
    }

    // 按部门统计满意度 逻辑一样
    @Override
    public ResponseResult comment_class() {
        // 查询到所有部门
        List<SchoolClass> schoolClasses = schoolClassMapper.findAllSchoolClasses();
        if(schoolClasses == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Map<String, Double> map = new HashMap<>();  // 返回对象
        Double[] score = new Double[1];  // 分数
        int[] count = new int[1];  // 意见数量

        // 用部门id去查询对应所有意见信息
        schoolClasses.forEach(schoolClass -> {  // 循环每个部门
            score[0] = 0.0;
            count[0] = 0;
            // 获取部门id
            int class_id = schoolClass.getId();
            // 查询到当前部门所有的意见信息
            List<ProblemPo> problemPos = problemMapper.getProblemIdByClassId(class_id);
            if(problemPos == null){
                score[0] = 100.0;
            }else{
                problemPos.forEach(problemPo -> {  // 循环当前部门所有的意见信息
                    int problem_id = problemPo.getId();
                    // 用意见id查询评价id
                    CommentPo commentPo = commentMapper.getCommentByProblemId(problem_id);
                    if(commentPo != null){
                        score[0] += commentPo.getScore();
                        count[0]++;
                    }
                });
                // 转换分值
                if(count[0] == 0){
                    score[0] = 100.0;
                }else{
                    score[0] = (score[0] / (count[0] * 5)) * 100;
                }
            }
            map.put(schoolClass.getClassName(), score[0]);
        });

        return ResponseResult.okResult(map);
    }
}
